/*
 * IDGenerator.java
 *
 * Created on 2007-9-17, pm5:28
 *
 * Create ID string by visit the table of T_IDProviderNew.
 *
 */

package orest.common.util;

import java.sql.*;
import java.util.HashMap;
import orest.common.util.Tools;

/**
 *
 * @author yan dongdong
 */
public class IDGenerator {
    
    private static HashMap GeneratorTable = new HashMap();
    private static String getLastIDSql =
                             "select CurID from  T_IDProvider where IDType=?";
    private static String updateCurIDSql =
                            "update  T_IDProvider set CurID=? where IDType=?";
    private static final String comStr = "000000000000";
    private static final String comStr1 = "00";

    
    private static int maxSize = 10;
    private static int maxSize2 = 1;
    private long baseId = 0;
    private int offset = 0;
    private String typeKey = "";
    private static String date = "";
    private static boolean check = true;
    
    /** Creates a new instance of IDGenerator */
    public IDGenerator () {
        
    }
    
    public synchronized String getID(int Key) {
        String curId = "";
        offset++;
        Tools tool = new Tools ();
        String temp = tool.getDateTime2 ();
        int remLength;
        String newid = "";
    //    System.out.println("baseId20100520"+baseId);
    //    System.out.println("date"+date);
        if ((offset < maxSize) && date.equals (temp)) {
            if(Key == 1) {
                if(baseId + offset >= 100)
                  //  return null;
                    initId ();
            }
            curId = String.valueOf (baseId + offset);
       //     System.out.println("baseId"+baseId);
       //     System.out.println("offset"+offset);
       //     System.out.println("aaaaaaaaaaaaaaa"+curId);
        } else {
            if((Key == 1 && baseId < 100) || Key == 2) {
                if(!date.equals ("") && !date.equals (temp))
                    this.check = false;
                offset = 0;
                initId ();
                curId = String.valueOf (baseId);
                this.date = temp;
            } else if (Key == 3 || Key == 4) {
                offset = 0;
                initId ();
                curId = String.valueOf (baseId);
            } else
                return null;
        }
     
        tool = null;
        
        if(Key == 1) {
            remLength = comStr1.length () - curId.length ();
            newid = temp + comStr1.substring (0, remLength) + curId;
		}
		 if (Key == 2) {
			remLength = comStr.length() - curId.length();
		    newid = temp + comStr.substring(0, remLength) + curId;
		}
        return newid;

    }
    
    public static IDGenerator getIDGenerator() throws Exception {
        IDGenerator generator = null;
        try {
          generator = getIDGenerator("Common");
        }
        catch (Exception e) {
          throw e;
        }
        return generator;
    }
    
    public static IDGenerator getIDGenerator(String typeKey) 
                                                             throws Exception {
        IDGenerator generator = null;
        generator = (IDGenerator) GeneratorTable.get(typeKey);
        if (generator == null) {
               PreparedStatement pstmt = null;
               Connection conn = null;

          try {
            conn = (new DataBase()).getSysConnectionPool ();
            pstmt = conn.prepareStatement(getLastIDSql);
            pstmt.setString(1, typeKey);
            ResultSet rs = pstmt.executeQuery();
            if (!rs.next()) {
              throw new Exception("not find the type of id!");
            }

          }
          catch (Exception e) {
            throw e;
          }
          generator = new IDGenerator(typeKey);
          GeneratorTable.put(typeKey, generator);
        }
        return generator;
    }
    
    protected IDGenerator(String typeKey) throws RestException {
        this.typeKey = typeKey;
        baseId = 0;
        offset = 0;
        initId();
    }
    
    private void initId() {
    
        PreparedStatement pstmt = null;
        Connection conn = null;

        try {
            conn = (new DataBase()).getSysConnectionPool ();
            if(!check) {
                System.out.println("I run");
                pstmt = conn.prepareStatement(updateCurIDSql);
                pstmt.setLong(1, 1);
                pstmt.setString(2, this.typeKey);
                if (pstmt.executeUpdate() == 0) {
                    throw new RestException("Update the id number failure!");
                }  
            }
            pstmt = conn.prepareStatement(getLastIDSql);
            pstmt.setString(1, this.typeKey);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                baseId = rs.getLong(1);
                System.out.println (baseId);
            }
            pstmt = conn.prepareStatement(updateCurIDSql);
             /******************Ϊ֪ͨ������ 20110525 begin********************/
            if (this.typeKey.equals("T_Notice") && (baseId + maxSize)>=100) {
            pstmt.setLong(1, 1);

            }
            if (((this.typeKey.equals("T_Notice")) && (baseId + maxSize)<100) || (!this.typeKey.equals("T_Notice"))) {
            pstmt.setLong(1, baseId + maxSize);

            }
             /******************Ϊ֪ͨ������ 20110525 end********************/
           // pstmt.setLong(1, baseId + maxSize);
            pstmt.setString(2, this.typeKey);
            if (pstmt.executeUpdate() == 0) {
                throw new RestException("Update the id number failure!");
            }  
            this.check = true;
        }
        catch (Exception e) {
            System.out.println("update ID failure  3");
            e.printStackTrace();
        }
        finally {
		    this.check = true;
            pstmt = null;
        }      
    }
    
}
